<template>
  <div class="app">
    <div class="headee">
      <div class="tx">
        <el-upload
            class="avatar-uploader"
            :headers="headers"
            :action="action"
            :show-file-list="false"
            :on-success="handleAvatarSuccess"
            :before-upload="beforeAvatarUpload">
          <img v-if="picture" :src="picture" class="tximg" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </div>
      <div class="contine">
        <h1>{{ Name }}</h1>
        <p>年龄: {{ age }}</p>
        <p>电话: {{ phone }}</p>
        <p>邮箱: {{ email }}</p>
        <p>简介：{{ introduction }}</p>
      </div>
      <div class="btn_edit">
        <el-button round type="info" icon="el-icon-edit"  @click="passwordUpdate()">
          修改密码
        </el-button>
      </div>
    </div>

    <!-- 时间范围开始 -->
    <el-row :gutter="12" style="margin-bottom:5px">
      <el-col :span="24">
        <el-card>
          <div style="text-align:center">
            <span>{{ schedulingData?.startTimeThisWeek }}(周一)</span>-<span>{{
              schedulingData?.endTimeThisWeek
            }}(周日)</span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    <!-- 时间范围结束 -->
    <div>
      <!-- 排班表格开始 -->
      <el-table v-loading="loading" :data="tableData" border :span-method="spanMethod">
        <el-table-column prop="userId" label="医生" align="center" :formatter="userFormatter"/>
        <el-table-column prop="deptId" label="科室" align="center" :formatter="deptFormatter"/>
        <el-table-column prop="subsectionType" label="时间/日期" align="center" :formatter="subsectionTypeFormatter"/>
        <el-table-column prop="schedulingType[0]" :label="labelNames[0]" align="center"
                         :formatter="schedulingTypeDay1Formatter"/>
        <el-table-column prop="schedulingType[1]" :label="labelNames[1]" align="center"
                         :formatter="schedulingTypeDay2Formatter"/>
        <el-table-column prop="schedulingType[2]" :label="labelNames[2]" align="center"
                         :formatter="schedulingTypeDay3Formatter"/>
        <el-table-column prop="schedulingType[3]" :label="labelNames[3]" align="center"
                         :formatter="schedulingTypeDay4Formatter"/>
        <el-table-column prop="schedulingType[4]" :label="labelNames[4]" align="center"
                         :formatter="schedulingTypeDay5Formatter"/>
        <el-table-column prop="schedulingType[5]" :label="labelNames[5]" align="center"
                         :formatter="schedulingTypeDay6Formatter"/>
        <el-table-column prop="schedulingType[6]" :label="labelNames[6]" align="center"
                         :formatter="schedulingTypeDay7Formatter"/>
      </el-table>
      <!-- 排班表格结束 -->
      <div>
        <el-dialog
            title="修改密码"
            :visible.sync="dialogVisible"

            @close="handleClose"
        >
          <el-form ref="changePasswordForm" :rules="rules"  :model="changePasswordForm" label-width="80px">

            <el-form-item label="新密码" label-width=100px prop="newPassword">
              <el-input v-model="changePasswordForm.newPassword" placeholder="请输入新密码" type="password"></el-input>
            </el-form-item>
            <el-form-item label="确认新密码" label-width=100px prop="confirmPassword">
              <el-input v-model="changePasswordForm.confirmPassword" placeholder="请确认密码" type="password"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </span>
        </el-dialog>
      </div>


    </div>


  </div>
</template>

<script>
import axios from "axios";

export default {
  data() {
    return {
      Name: "",
      age: "",
      phone: "",
      email: "",
      introduction: "",
      picture: "",
      // 遮罩层
      loading: false,
      // 科室数据
      deptOptions: [],
      // 用户数据
      userOptions: [],
      // 排班时间段字典
      subsectionTypeOptions: [],
      // 排班类型字典
      schedulingTypeOptions: [],
      queryParams: {
        userId: null // 当前用户ID
      },
      // 查询条件
      schedulingData: {
        startTimeThisWeek: undefined,
        endTimeThisWeek: undefined
      },
      // 排班表的数据   应该从后台查询
      tableData: [],
      // 表头数据
      labelNames: ['', '', '', '', '', '', ''],

      dialogVisible: false,
      changePasswordForm: {
        newPassword: undefined,
        confirmPassword: undefined
      },
      addVisible: false,
      // 图片上传的请求头
      headers: {
        token: sessionStorage.getItem("token")
      },
      action: axios.defaults.baseURL + "/system/user/uploadOos",
      // 表单校验
      rules: {
        newPassword: [
          { required: true, message: "新密码不能为空", trigger: "blur" },
          { min: 6, max: 20, message: "长度在 6 到 20 个字符", trigger: "blur" }
        ],
        confirmPassword: [
          { required: true, message: "确认密码不能为空", trigger: "blur" },

        ]
      }

    };
  },
  created() {
    this.loadUser();
    this.loadDept();
    this.loadUsers();
    this.listScheduling();
    this.listSubsectionType();
    this.listSchedulingType();
  },
  computed: {
    groupNum() { // 获取医生列表数组
      return new Set(this.tableData.map(o => o.userId))
    }
  },
  methods: {
    handleAvatarSuccess(res, file) {
      this.picture = res.data;
      console.log(this.picture);
      this.$http.post("/system/user/update", {
        userId: this.userId,
        picture: this.picture
      }).then(res => {
        this.$message({
          message: '修改成功',
          type: 'success'
        });
      })
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png';
      const isLt5M = file.size / 1024 / 1024 < 5;  // 修改为 5MB 限制
      if (!isJPG) {
        this.$message.error('上传图片只能是 JPG 或 PNG 格式!');
        return false;
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
        return false;
      }
      return true;
    },

    loadUser() {
      /*获取个人信息*/
      this.$http.get("/system/user/info").then(res=>{
        this.Name = res.data.data.userName;
        this.age = res.data.data.age;
        this.phone = res.data.data.phone;
        this.email = res.data.data.email;
        this.introduction = res.data.data.introduction;
        this.picture = res.data.data.picture;
        this.userId = res.data.data.userId
        this.listScheduling(this.userId)

        // this.userInfo = res.data
      });
    },
    // 点击修改密码
    passwordUpdate(){
      this.dialogVisible = true;
    },
    listSchedulingType() {
      this.$http.get("/system/dict/data/type/his_scheduling_type").then(resp => {
        this.schedulingTypeOptions = resp.data.data;
      });
    },
    listSubsectionType() {
      this.$http.get("/system/dict/data/type/his_subsection_type").then(resp => {
        this.subsectionTypeOptions = resp.data.data;
      });
    },
    listScheduling(userId) {
      this.queryParams.userId = userId;
      this.$http.post("/doctor/scheduling/selectScheduling", this.queryParams).then(resp => {
        this.schedulingData.startTimeThisWeek = resp.data.data.startTimeThisWeek;
        this.schedulingData.endTimeThisWeek = resp.data.data.endTimeThisWeek;
        this.tableData = resp.data.data.schedulingDtos;
        this.labelNames = resp.data.data.labelNames;
      }).catch(error => {
        console.error("获取排班信息失败", error);
      });
    },
    loadDept() {
      this.$http.get("/system/dept/list").then(resp => {
        this.deptOptions = resp.data.data;
      });
    },
    loadUsers() {
      this.$http.get("/system/user/listAll").then(resp => {
        this.userOptions = resp.data.data;
      });
    },
    handleQuery() {
      this.listScheduling();
    },
    userFormatter(row) {
      let name = '';
      this.userOptions.forEach(item => {
        if (row.userId === item.userId) {
          name = item.userName;
        }
      });
      return name;
    },
    deptFormatter(row) {
      let name = '';
      this.deptOptions.forEach(item => {
        if (row.deptId === item.deptId) {
          name = item.deptName;
        }
      });
      return name;
    },
    subsectionTypeFormatter(row) {
      let name = "";
      this.subsectionTypeOptions.forEach(item => {
        if (item.dictValue == row.subsectionType) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay1Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[0]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay2Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[1]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay3Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[2]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay4Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[3]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay5Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[4]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay6Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[5]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    schedulingTypeDay7Formatter(row) {
      let name = "";
      this.schedulingTypeOptions.forEach(item => {
        if (item.dictValue == row.schedulingType[6]) {
          name = item.dictLabel;
        }
      });
      return name;
    },
    spanMethod(data) {
      const { row, rowIndex, columnIndex } = data;
      if (columnIndex < 2 || columnIndex > 9) {
        const len = this.userGroup(row.userId);
        const lenName = this.userIdLen(row.userId);
        if (rowIndex === lenName) {
          return {
            rowspan: len,
            colspan: 1
          };
        } else {
          return {
            rowspan: 0,
            colspan: 0
          };
        }
      } else {
        return {
          rowspan: 1,
          colspan: 1
        };
      }
    },
    userGroup(name) {
      return this.tableData.filter(o => o.userId === name).length;
    },
    userIdLen(name) {
      const tmp = Array.from(this.groupNum);
      const index = tmp.indexOf(name);
      let len = 0;
      for (let i = 0; i < index; i++) {
        len += this.userGroup(tmp[i]);
      }
      return len;
    },


    handleClose() {
      this.dialogVisible = false;
      // 清空表单
      // this.$refs.changePasswordForm.resetFields();
    },
    handleSubmit() {
      let confirmPassword = this.changePasswordForm.confirmPassword;
      let newPassword = this.changePasswordForm.newPassword;

      if (confirmPassword === newPassword) {
        // 使用请求体发送数据，而不是查询参数
        const postData = {
          userId: this.userId,
          password: newPassword
        };
        console.log(postData)
        // 发送POST请求
        this.$http.post('/system/user/updatePassword', postData).then(response => {
          // 清空表单
          this.$refs.changePasswordForm.resetFields();
          // 显示成功消息并在3秒后登出
          this.$message.success("修改成功，3秒后自动退出");
          setTimeout(() => {
            this.loginOut();
          }, 3000);
          // 关闭弹出框
          this.dialogVisible = false;
        }).catch(error => {
          // 错误处理
          this.$message.error("更新密码失败");
        });

      } else {
        this.$message.error("两次密码输入不一致");
      }
    },

    loginOut(){
      this.$router.push("/")
    }
  },
};
</script>

<style>
.app {
  font-family: 'Avenir', Helvetica, Arial, sans-serif;
  color: #34495e;
  margin-top: 20px;
  padding: 0 20px;
}

h1 {
  font-size: 2.5em;
  margin-bottom: 10px;
  color: #2c3e50;
}

p {
  font-size: 1.2em;
  margin-bottom: 8px;
}

.headee {
  display: flex;
  background: #f7f9fa;
  border-radius: 10px;
  padding: 20px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
}

.tx {
  height: 200px;
  width: 200px;
  margin: 0 20px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.tximg {
  width: 180px;
  height: 180px;
  border-radius: 50%;
  object-fit: cover;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.contine {
  flex: 1;
  margin: 0 20px;
}

.btn_edit {
  height: 200px;
  width: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
}

.el-button {
  font-size: 1.1em;
  padding: 10px 20px;
}

.el-row {
  margin-bottom: 10px;
}

.el-table {
  border-radius: 10px;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
}

.el-card {
  border-radius: 10px;
}

.el-dialog {
  border-radius: 10px;
}

.el-input {
  border-radius: 5px;
}

.el-button--primary {
  background-color: #1abc9c;
  border-color: #1abc9c;
}

.el-button--primary:hover {
  background-color: #16a085;
  border-color: #16a085;
}

</style>